package com.vehicle.admin.web.common.shiro.filter;

import com.google.common.collect.Maps;
import com.vehicle.common.util.WebHelper;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Created by yantingbin on 2017/7/19.
 */
@Component
public class PermissionFilter extends AccessControlFilter {
    private static final String LOGIN_URL = "/sys/user/login";
    private static final String UNAUTHORIZED_URL = "/sys/user/unauthorized";

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        Subject subject = getSubject(servletRequest, servletResponse);

        if (null != o) {
            String[] arr = (String[]) o;
            for (String per : arr) {
                if (subject.isPermitted(per)) {
                    return Boolean.TRUE;
                }
            }
        }

        HttpServletRequest httpServletRequest = ((HttpServletRequest) servletRequest);

        String uri = httpServletRequest.getRequestURI();
        String basePath = httpServletRequest.getContextPath();

        if (uri != null && uri.startsWith(basePath)) {
            uri = uri.replace(basePath, "");
        }

        if (subject.isPermitted(uri)) {
            return Boolean.TRUE;
        }

        if (WebHelper.isAjax((HttpServletRequest) servletRequest)) {
            Map<String, String> resultMap = Maps.newHashMap();
            resultMap.put("login_status", String.valueOf(HttpServletResponse.SC_MULTIPLE_CHOICES));
            resultMap.put("message", "当前用户未登录");
            WebHelper.out((HttpServletResponse) servletResponse, resultMap);
        }
        return Boolean.FALSE;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        Subject subject = getSubject(servletRequest, servletResponse);
        if (subject.getPrincipal() == null) {
            saveRequest(servletRequest);
            WebUtils.issueRedirect(servletRequest, servletResponse, LOGIN_URL);
        } else {
            if (StringUtils.hasText(UNAUTHORIZED_URL)) {
                WebUtils.issueRedirect(servletRequest, servletResponse, UNAUTHORIZED_URL);
            } else {
                WebUtils.toHttp(servletResponse).sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }
        }
        return Boolean.FALSE;
    }
}
